package String;

import org.junit.Test;

/**
 * @Classname 分割两个字符串得到回文串1616
 * @Description TODO
 * @Date 2023/3/18 9:48
 * @Created by xjl
 */
public class 分割两个字符串得到回文串1616 {

    @Test
    public void test(){
        boolean b = checkPalindromeFormation("abdef", "fecab");
        System.out.println(b);
    }

    /**
     * @description 双指针思路
      * @param: a
     * @param: b
     * @date: 2023/3/18 10:09
     * @return: boolean
     * @author: xjl
    */
    public boolean checkPalindromeFormation2(String a, String b) {
        return checkConcatenation(a, b) || checkConcatenation(b, a);
    }

    private boolean checkConcatenation(String a, String b) {
        int n = a.length();
        int left = 0, right = n - 1;
        while (left < right && a.charAt(left) == b.charAt(right)) {
            left++;
            right--;
        }
        // 如果left大于right 表示在a[0-left] b[rgiht,n]能够回文串
        if (left >= right) {
            return true;
        }
        // 如果没有到left=right的时候 就把整个为了三个部分，前面a[0-left] b[rgiht,n]都是相等于的，那后如果是回文就需要保证a[left,right] 或者b[left,right]是回文，连接以后那就一定是回文字符
        return checkSelfPalindrome(a, left, right) || checkSelfPalindrome(b, left, right);
    }

    private boolean checkSelfPalindrome(String a, int left, int right) {
        while (left < right && a.charAt(left) == a.charAt(right)) {
            left++;
            right--;
        }
        return left >= right;
    }

    /**
     * @description 暴力超时结果
      * @param: a
     * @param: b
     * @date: 2023/3/18 9:59
     * @return: boolean
     * @author: xjl
    */
    public boolean checkPalindromeFormation(String a, String b) {
        if (check(a)||check(b)){
            return true;
        }
        for (int i=0;i<a.length();i++){
            String pre_a=a.substring(0,i);
            String suf_a=a.substring(i,a.length());
            String pre_b=b.substring(0,i);
            String suf_b=b.substring(i,b.length());
            if (check(pre_a+suf_b)||check(pre_b+suf_a)){
                return true;
            }
        }
        return false;
    }

    /**
     * @description 判断字符是否为回文
     * @param: s
     * @date: 2023/3/18 9:49
     * @return: boolean
     * @author: xjl
     */
    public boolean check(String s) {
        if (s.length() == 0) {
            return true;
        }
        int left = 0;
        int right = s.length() - 1;
        while (left <= right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}
